<template>
  <div class="works-container">
    <!-- 页面标题和操作区 -->
    <div class="page-header" v-if="!isVisitorMode">
      <h2 class="page-title">我的作品管理</h2>
      <a-button type="primary" class="upload-btn" @click="openUploadModal">
        <template #icon><UploadOutlined /></template>
        上传作品
      </a-button>
    </div>

    <!-- 访客模式标题 -->
    <div class="page-header" v-else>
      <h2 class="page-title">作品展示</h2>
    </div>

    <!-- 筛选条件 -->
    <div class="filter-bar" v-if="!isVisitorMode">
      <a-select
          v-model:value="statusFilter"
          placeholder="作品状态"
          style="width: 150px; margin-right: 10px"
          @change="handleFilterChange"
      >
        <a-select-option value="">全部状态</a-select-option>
        <a-select-option value="1">草稿</a-select-option>
        <a-select-option value="2">审核中</a-select-option>
        <a-select-option value="3">已发布</a-select-option>
        <a-select-option value="4">下架</a-select-option>
        <a-select-option value="5">驳回</a-select-option>
      </a-select>

      <a-select
          v-model:value="chargeFilter"
          placeholder="收费状态"
          style="width: 150px; margin-right: 10px"
          @change="handleFilterChange"
      >
        <a-select-option value="">全部</a-select-option>
        <a-select-option value="0">免费</a-select-option>
        <a-select-option value="1">收费</a-select-option>
      </a-select>

      <a-input
          v-model:value="searchKeyword"
          placeholder="搜索作品名称"
          style="width: 200px"
          allow-clear
          @pressEnter="handleSearch"
      >
        <template #suffix>
          <SearchOutlined @click="handleSearch" />
        </template>
      </a-input>
    </div>

    <!-- 引入上传组件 -->
    <WorkUploadModal ref="uploadModal" @upload="handleUpload" @refresh="fetchWorksList" v-if="!isVisitorMode" />

    <!-- 作品列表 -->
    <div class="works-container">
      <!-- 加载状态 -->
      <div v-if="isLoading" class="loading-container">
        <Spin size="large" tip="加载中..." />
      </div>

      <!-- 空状态 -->
      <div v-else-if="works.length === 0" class="empty-container">
        <Empty description="暂无作品数据" />
        <a-button v-if="!isVisitorMode" type="primary" style="margin-top: 16px" @click="openUploadModal">
          上传第一个作品
        </a-button>
      </div>

      <!-- 列表内容 -->
      <div v-else class="works-grid">
        <div class="work-card" v-for="(work, index) in works" :key="work.id" @click="openDetail(work)">
          <div class="work-status" :class="getStatusClass(work.status)">
            {{ getStatusText(work.status) }}
          </div>

          <img :src="minioUrl + work.coverFileUrl" alt="作品封面" class="work-cover" />

          <div class="work-info">
            <h3 class="work-title" :title="work.worksName">{{ work.worksName }}</h3>

            <div class="work-tags">
              <a-tag
                  v-for="(tag, i) in work.tags?.split(',') || []"
                  :key="i"
                  color="blue"
                  size="small"
                  v-if="tag"
              >
                {{ tag }}
              </a-tag>
            </div>

            <p class="work-desc" :title="work.description">{{ work.description }}</p>

            <div class="work-meta">
              <span>
                <CalendarOutlined /> {{ formatDate(work.createTime) }}
              </span>
              <span v-if="work.isCharge === 1" class="price-tag">
                ¥{{ work.price || 0 }}元
              </span>
              <span v-else class="free-tag">免费</span>
            </div>

            <div class="work-actions" v-if="!isVisitorMode">
              <a-button size="small" @click.stop="editWork(work)">
                <EditOutlined /> 编辑
              </a-button>
              <a-button
                  size="small"
                  danger
                  @click.stop="handleDeleteConfirm(work.id)"
              >
                <DeleteOutlined /> 删除
              </a-button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 分页控制器（Ant Design Vue 官方组件） -->
    <div class="pagination-container" v-if="total > 0 && !isLoading && !isVisitorMode">
      <Pagination
          v-model:current="pageNum"
          :pageSize="pageSize"
          :total="total"
          show-size-changer
          show-quick-jumper
          :show-total="(total) => `共 ${total} 条记录`"
          @change="handlePageChange"
          @showSizeChange="handlePageSizeChange"
      />
    </div>

    <!-- 作品详情弹窗 -->
    <a-modal
        v-model:visible="detailVisible"
        title="作品详情"
        width="900px"
        destroyOnClose
        @cancel="handleDetailCancel"
    >
      <div v-if="currentWork" class="detail-content">
        <!-- 视频播放区域 -->
        <div class="video-container">
          <video
              :src="minioUrl + currentWork.videoUrl"
              class="work-video"
              controls
              :poster="minioUrl + currentWork.coverFileUrl"
              preload="metadata"
              :alt="currentWork.worksName + '的视频'"
          >
            您的浏览器不支持视频播放
          </video>
        </div>

        <!-- 作品信息区域 -->
        <div class="detail-info">
          <h2 class="detail-title">{{ currentWork.worksName }}</h2>

          <div class="detail-status">
        <span :class="getStatusClass(currentWork.status)">
          {{ getStatusText(currentWork.status) }}
        </span>
          </div>

          <p class="detail-desc">{{ currentWork.description || '无描述' }}</p>

          <div class="detail-tags">
            <a-tag
                v-for="(tagName, i) in workTagMap[currentWork.id] || []"
                :key="i"
                color="blue"
                size="small"
                v-if="tagName"
            >
              {{ tagName }}
            </a-tag>
          </div>

          <div class="detail-meta">
            <div class="meta-item">
              <CalendarOutlined />
              <span>创建时间：{{ formatDate(currentWork.createTime) }}</span>
            </div>
            <div class="meta-item">
          <span v-if="currentWork.isCharge === 1" class="price-tag">
            收费：{{ currentWork.price || 0 }}元
          </span>
              <span v-else class="free-tag">
            免费
          </span>
            </div>
          </div>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue';
import { message, Modal, Spin, Empty, Pagination } from 'ant-design-vue';
import {
  UploadOutlined, SearchOutlined, CalendarOutlined,
  EditOutlined, DeleteOutlined
} from '@ant-design/icons-vue';
import WorkUploadModal from './WorkUploadModal.vue';
import { deleteWorks, getWorksList } from '@/api/media/bizWorksController';

// 组件属性
interface Props {
  works?: any[] // 外部传入的作品数据
  loading?: boolean // 外部传入的加载状态
  isVisitorMode?: boolean // 是否为访客模式
}

const props = withDefaults(defineProps<Props>(), {
  works: () => [],
  loading: false,
  isVisitorMode: false
})

// 组件事件
const emit = defineEmits<{
  workClick: [work: any]
}>()

const pageNum = ref(1); // 当前页码（与后端保持一致，从1开始）
const pageSize = ref(10);    // 每页条数
const total = ref(0);      // 总记录数（后端返回）
const isLoading = ref(props.loading); // 加载状态

// 作品类型定义（与后端BizWorksVo对应）
interface Work {
  id: number;
  userId: number;
  worksName: string;
  coverFileUrl: string;
  description: string;
  tags: string;
  isCharge: number;
  price: number;
  status: number;
  fileMd5: string;
  createTime: string;
  updateTime: string;
  deleted: number;
  videoUrl: string;
  views?: number;
}

// 分页查询参数类型（与后端WorksPageQuery完全匹配）
interface WorksPageQuery {
  pageNum: number;      // 页码，从1开始
  pageSize: number;     // 每页条数
  isCharge?: number;    // 0-免费 1-收费
  status?: number;      // 作品状态
  worksName?: string;   // 作品名称（模糊查询）
  userId?: number;      // 当前登录用户ID
}

// 分页结果类型（与后端返回结构匹配）
interface PageResult<T> {
  list: T[];            // 当前页数据列表
  total: number;        // 总记录数
  size: number;         // 每页条数
  current: number;      // 当前页码
  pages: number;        // 总页数
}

// 引入标签Store和用户信息
import { useTagStore } from '@/stores/worksTagStore';
const tagStore = useTagStore();

// 状态管理
const works = ref<Work[]>(props.works);
const uploadModal = ref<InstanceType<typeof WorkUploadModal>>();
const minioUrl = import.meta.env.VITE_MINIO_URL;

// 筛选条件
const statusFilter = ref('');
const chargeFilter = ref('');
const searchKeyword = ref('');

// 标签映射和详情弹窗状态
const workTagMap = ref<Record<number, string[]>>({});
const detailVisible = ref(false);
const currentWork = ref<Work | null>(null);

// 监听外部works变化
watch(() => props.works, (newWorks) => {
  if (newWorks && newWorks.length > 0) {
    works.value = newWorks;
    resolveAllWorkTags();
  }
})

// 监听外部loading变化
watch(() => props.loading, (newLoading) => {
  isLoading.value = newLoading;
})

// 打开详情弹窗
const openDetail = (work: Work) => {
  currentWork.value = work;
  detailVisible.value = true;
  // 触发外部事件
  emit('workClick', work);
};

// 关闭详情弹窗
const handleDetailCancel = () => {
  detailVisible.value = false;
  currentWork.value = null;
};

// 页面加载时初始化
onMounted(async () => {
  await tagStore.fetchAndSaveTags();
  
  // 访客模式下不自动获取数据，使用外部传入的数据
  if (!props.isVisitorMode) {
    await fetchWorksList();
  } else if (props.works && props.works.length > 0) {
    // 访客模式下，如果有外部数据，解析标签
    await resolveAllWorkTags();
  }
});

// 获取作品列表（修复分页核心逻辑）
const fetchWorksList = async () => {
  try {
    isLoading.value = true;

    // 构建查询参数（严格匹配后端接口要求）
    const queryParams: WorksPageQuery = {
      pageNum: pageNum.value,  // 直接使用当前页码（已从1开始）
      pageSize: pageSize.value,
    };

    // 状态筛选（非空才添加）
    if (statusFilter.value) {
      queryParams.status = Number(statusFilter.value);
    }

    // 收费状态筛选（非空才添加）
    if (chargeFilter.value) {
      queryParams.isCharge = Number(chargeFilter.value);
    }

    // 作品名称搜索（非空才添加）
    if (searchKeyword.value) {
      queryParams.worksName = searchKeyword.value;
    }

    // 调用后端接口
    console.log('请求分页参数:', queryParams);  // 调试用，可删除
    const response = await getWorksList(queryParams);

    if (response.code === '00000' && response.data) {
      const pageResult: PageResult<Work> = response.data;
      works.value = pageResult.list || [];
      total.value = pageResult.total || 0;
      pageNum.value = pageResult.pages || 0;
      await resolveAllWorkTags();
    } else {
      message.error('获取作品列表失败: ' + (response.message || '未知错误'));
      works.value = [];
    }
  } catch (error) {
    console.error('获取作品列表出错:', error);
    message.error('网络错误，获取作品列表失败');
  } finally {
    isLoading.value = false;
  }
};

// 解析作品标签
const resolveWorkTags = async (work: Work) => {
  if (!work.tags) {
    workTagMap.value[work.id] = [];
    return;
  }

  const tagIds = work.tags.split(',').map(Number).filter(Boolean);
  if (tagIds.length === 0) {
    workTagMap.value[work.id] = [];
    return;
  }

  const tags = await tagStore.fetchTagsByIds(tagIds);
  workTagMap.value[work.id] = tags.map(tag => tag.name);
};

// 批量解析标签
const resolveAllWorkTags = async () => {
  for (const work of works.value) {
    await resolveWorkTags(work);
  }
};

// 分页变更处理
const handlePageChange = (page: number) => {
  console.log('切换到页码:', page);  // 调试用
  pageNum.value = page;
  fetchWorksList();  // 页码变化时重新请求数据
};

// 每页条数变更处理
const handlePageSizeChange = (current: number, size: number) => {
  console.log('每页条数变更为:', size);  // 调试用
  pageSize.value = size;
  pageNum.value = 1;  // 重置到第一页
  fetchWorksList();       // 重新请求数据
};

// 搜索处理
const handleSearch = () => {
  pageNum.value = 1;  // 搜索时重置到第一页
  fetchWorksList();
};

// 筛选条件变化处理
const handleFilterChange = () => {
  pageNum.value = 1;  // 筛选时重置到第一页
  fetchWorksList();
};

// 打开上传弹窗
const openUploadModal = () => {
  uploadModal.value?.open();
};

// 处理上传成功
const handleUpload = (newWork: Partial<Work>) => {
  message.success('上传成功');
  fetchWorksList();
};

// 编辑作品
const editWork = (work: Work) => {
  uploadModal.value?.open(work);
};

// 删除确认
const handleDeleteConfirm = (id: number) => {
  Modal.confirm({
    title: '确认删除',
    content: '确定要删除这个作品吗？此操作不可撤销。',
    okText: '确认',
    cancelText: '取消',
    onOk: () => deleteWork(id)
  });
};

// 删除作品
const deleteWork = async (id: number) => {
  try {
    isLoading.value = true;
    await deleteWorks(id);
    message.success('删除成功');

    // 删除后如果当前页没有数据了，自动返回上一页
    if (works.value.length === 1 && pageNum.value > 1) {
      pageNum.value--;
    }
    await fetchWorksList();
  } catch (error) {
    console.error('删除作品失败:', error);
    message.error('删除失败，请重试');
  } finally {
    isLoading.value = false;
  }
};

// 格式化日期
const formatDate = (dateString: string) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  return date.toLocaleDateString();
};

// 状态文本映射
const getStatusText = (status: number) => {
  const statusMap: Record<number, string> = {
    1: '草稿',
    2: '审核中',
    3: '已发布',
    4: '下架',
    5: '驳回'
  };
  return statusMap[status] || '未知';
};

// 状态样式映射
const getStatusClass = (status: number) => {
  const classMap: Record<number, string> = {
    1: 'status-draft',
    2: 'status-review',
    3: 'status-published',
    4: 'status-offline',
    5: 'status-rejected'
  };
  return classMap[status] || 'status-unknown';
};
</script>

<style scoped>
.works-container {
  width: 100%;
  background: #0b2b5b;
  min-height: 600px;
  padding: 20px;
  color: #fff;
}

/* 页面头部 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
}

.upload-btn {
  background: #2f80ed;
  border: none;
}

/* 筛选栏 */
.filter-bar {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding: 15px;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 6px;
  flex-wrap: wrap;
}

/* 加载和空状态 */
.loading-container, .empty-container {
  width: 100%;
  padding: 80px 0;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

/* 作品网格布局 */
.works-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

/* 作品卡片 */
.work-card {
  background: #0f3a72;
  border-radius: 8px;
  padding: 10px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  transition: transform 0.2s ease, box-shadow 0.2s ease;
  position: relative;
  cursor: pointer;
}

.work-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.3);
}

/* 作品状态标签 */
.work-status {
  position: absolute;
  top: 10px;
  right: 10px;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
  z-index: 1;
}

.status-draft { background: #8c8c8c; }
.status-review { background: #faad14; }
.status-published { background: #52c41a; }
.status-offline { background: #1890ff; }
.status-rejected { background: #f5222d; }
.status-unknown { background: #722ed1; }

.work-cover {
  width: 100%;
  height: 120px;
  object-fit: cover;
  border-radius: 4px;
  margin-bottom: 10px;
}

.work-info {
  display: flex;
  flex-direction: column;
}

.work-title {
  font-size: 16px;
  font-weight: bold;
  margin: 0 0 8px 0;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.work-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  margin-bottom: 6px;
}

.work-desc {
  font-size: 12px;
  color: #c9d8e9;
  margin: 0 0 8px 0;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  height: 32px;
}

.work-meta {
  font-size: 12px;
  color: #9eb6d0;
  margin: 0 0 10px 0;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  align-items: center;
}

.work-meta span {
  display: flex;
  align-items: center;
  gap: 4px;
}

.price-tag {
  color: #ff4d4f;
  font-weight: 500;
}

.free-tag {
  color: #52c41a;
  background: rgba(82, 196, 26, 0.1);
  padding: 0 4px;
  border-radius: 2px;
}

.work-actions {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
  margin-top: auto;
}

/* 分页容器 */
.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  padding: 10px;
}

/* 详情弹窗样式 */
.detail-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
  padding: 10px 0;
}

.video-container {
  width: 100%;
  border-radius: 8px;
  overflow: hidden;
  background-color: #000;
}

.work-video {
  width: 100%;
  min-height: 400px;
  object-fit: contain;
}

.detail-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.detail-title {
  margin: 0;
  font-size: 22px;
  font-weight: 600;
  color: #1f2329;
}

.detail-status {
  display: inline-block;
  width: fit-content;
}

.detail-status span {
  padding: 3px 10px;
  border-radius: 12px;
  font-size: 14px;
}

.detail-desc {
  margin: 0;
  line-height: 1.6;
  color: #4e5969;
  font-size: 14px;
  min-height: 60px;
}

.detail-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  padding: 5px 0;
}

.detail-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  margin-top: 10px;
  color: #86909c;
  font-size: 14px;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 6px;
}

/* 复用状态样式 */
:deep(.detail-status .status-draft) {
  background: #8c8c8c;
  color: white;
}

:deep(.detail-status .status-review) {
  background: #faad14;
  color: white;
}

:deep(.detail-status .status-published) {
  background: #52c41a;
  color: white;
}

:deep(.detail-status .status-offline) {
  background: #1890ff;
  color: white;
}

:deep(.detail-status .status-rejected) {
  background: #f5222d;
  color: white;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .filter-bar {
    flex-direction: column;
    align-items: stretch;
    gap: 10px;
  }

  .filter-bar > * {
    width: 100% !important;
    margin-right: 0 !important;
  }

  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .work-video {
    min-height: 250px;
  }

  .works-grid {
    grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
  }
}
</style>
